﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TWCRM.Models.Home;
using TWCRM.Entity;
using System.Text;

namespace TWCRM.Controllers
{
    public class HomeController : Controller
    {
        private bool checkAuthority(string authority)
        {
            if (Session["PC-UserID"] == null)
                return false;

            return Convert.ToBoolean(Session[authority]);
        }

        private bool checkLogin()
        {
            if (Session["PC-UserID"] == null)
                return false;
            return true;
        }

        public ActionResult Index()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");

            IndexModel model = new IndexModel();
            model.CustomerMgt = checkAuthority(ConstAuthority.CUSTOMER_MGT);
            model.OrderMgt = checkAuthority(ConstAuthority.ORDER_MGT);
            model.ProductMgt = checkAuthority(ConstAuthority.PRODUCT_MGT);
            model.AccountMgt = checkAuthority(ConstAuthority.ACCOUNT_MGT);

            return View(model);
        }

        public ActionResult Login()
        {
            LoginModel model = new LoginModel();
            return View(model);
        }

        [HttpPost]
        public ActionResult Login(LoginModel model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    TWCRMEntities entities = new TWCRMEntities();


                    var user = (from u in entities.Users
                                where u.Name.Trim() == model.UserName
                                select u).SingleOrDefault();
                    if (user == null)
                    {
                        ModelState.AddModelError("UserName", "您提供的使用者名稱不正確");
                        return View(model);
                    }

                    if (user.Password.Trim() != model.Password)
                    {
                        ModelState.AddModelError("Password", "您提供的密碼不正確");
                        return View(model);
                    }

                    Session["PC-User"] = user.Name;
                    Session["PC-UserID"] = user.ID;
                    Session[ConstAuthority.CUSTOMER_MGT] = (from ua in entities.UserAuthorities
                                                            where ua.UserID == user.ID && ua.Authority == ConstAuthority.CUSTOMER_MGT
                                                            select ua).SingleOrDefault().Allow;
                    Session[ConstAuthority.ORDER_MGT] = (from ua in entities.UserAuthorities
                                                         where ua.UserID == user.ID && ua.Authority == ConstAuthority.ORDER_MGT
                                                         select ua).SingleOrDefault().Allow;
                    Session[ConstAuthority.PRODUCT_MGT] = (from ua in entities.UserAuthorities
                                                           where ua.UserID == user.ID && ua.Authority == ConstAuthority.PRODUCT_MGT
                                                           select ua).SingleOrDefault().Allow;
                    Session[ConstAuthority.ACCOUNT_MGT] = (from ua in entities.UserAuthorities
                                                           where ua.UserID == user.ID && ua.Authority == ConstAuthority.ACCOUNT_MGT
                                                           select ua).SingleOrDefault().Allow;

                    return this.RedirectToAction("Index", "Home");

                }
                return View(model);
            }
            catch (System.Reflection.ReflectionTypeLoadException ex)
            {
                StringBuilder sb = new StringBuilder();
                foreach (var ee in ex.LoaderExceptions)
                    sb.AppendLine(ee.Message);
                throw new Exception(sb.ToString());
            }
        }

        public ActionResult Logout()
        {
            Session["PC-User"] = null;
            Session["PC-UserID"] = null;
            Session[ConstAuthority.CUSTOMER_MGT] = null;
            Session[ConstAuthority.ORDER_MGT] = null;
            Session[ConstAuthority.PRODUCT_MGT] = null;
            Session[ConstAuthority.ACCOUNT_MGT] = null;
            return this.RedirectToAction("Login");
        }

        public ActionResult ChangePassword()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");

            ChangePasswordModel model = new ChangePasswordModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");

            if (model.Password != model.ConfirmPassword)
                ModelState.AddModelError("Password", "密碼不相符");

            if (ModelState.IsValid)
            {
                Guid userID = new Guid(Session["PC-UserID"].ToString());
                TWCRMEntities entities = new TWCRMEntities();
                var user = (from u in entities.Users
                            where u.ID == userID
                            select u).SingleOrDefault();

                if (user.Password.Trim() != model.OldPassword)
                {
                    ModelState.AddModelError("OldPassword", "您提供的密碼不正確");
                    return View(model);
                }

                user.Password = model.Password;
                entities.SaveChanges();

                return this.RedirectToAction("Index", new { Message = "修改密碼完成" });
            }

            return View(model);
        }

        public ActionResult CustomerMgt()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            return View();
        }

        public JsonResult GetCustomers()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);


            TWCRMEntities entities = new TWCRMEntities();

            var element = (from c in entities.Customers
                           select c).ToList();

            List<CustomerDisplayModel> list = new List<CustomerDisplayModel>();

            foreach (var c in element)
            {
                CustomerDisplayModel cdm = new CustomerDisplayModel();

                cdm.ID = c.ID;
                cdm.FirstName = c.FirstName;
                cdm.LastName = c.LastName;
                cdm.Company = c.Company;

                var phones = (from p in entities.Phones
                              where p.CustomerID == c.ID
                              select p);

                cdm.Phone1 = (from p in phones
                              where p.Type == "商務"
                              select p).SingleOrDefault().Phone1;
                cdm.Phone2 = (from p in phones
                              where p.Type == "商務傳真"
                              select p).SingleOrDefault().Phone1;
                cdm.Phone3 = (from p in phones
                              where p.Type == "住宅"
                              select p).SingleOrDefault().Phone1;
                cdm.Phone4 = (from p in phones
                              where p.Type == "移動電話"
                              select p).SingleOrDefault().Phone1;

                list.Add(cdm);
            }

            return Json(new { List = list }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult CustomerEdit(Guid? id)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            TWCRMEntities entities = new TWCRMEntities();
            CustomerModel model = new CustomerModel();

            if (id == null)
            {
                model.IsNew = true;
                model.PhoneList = new List<Phone>();
                model.EMailList = new List<EMail>();
                model.AddressList = new List<Address>();
            }
            else
            {
                var element = (from c in entities.Customers
                               where c.ID == id
                               select c).SingleOrDefault();

                if (element == null)
                {
                    return this.RedirectToAction("CustomerMgt", new { Error = "找不到這個客戶" });
                }

                model.PhoneList = (from p in entities.Phones
                                   where p.CustomerID == id
                                   select p).ToList();

                model.EMailList = (from e in entities.EMails
                                   where e.CustomerID == id
                                   select e).ToList();

                model.AddressList = (from a in entities.Addresses
                                     where a.CustomerID == id
                                     select a).ToList();

                model.FirstName = element.FirstName;
                model.LastName = element.LastName;
                model.Company = element.Company;
                model.Department = element.Department;
                model.Position = element.Position;
                model.Memo = element.Memo;
                model.ID = element.ID;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult CustomerEdit(CustomerModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            if (ModelState.IsValid)
            {
                TWCRMEntities entities = new TWCRMEntities();

                Customer customer;
                if (model.IsNew)
                {
                    customer = new Customer();
                    customer.ID = Guid.NewGuid();
                    entities.Customers.AddObject(customer);
                }
                else
                {
                    customer = (from c in entities.Customers
                                where c.ID == model.ID
                                select c).SingleOrDefault();
                    if (customer == null)
                        return RedirectToAction("CustomerMgt", new { Error = "找不到這個客戶" });
                }

                customer.FirstName = model.FirstName == null ? "" : model.FirstName;
                customer.LastName = model.LastName == null ? "" : model.LastName;
                customer.Company = model.Company == null ? "" : model.Company;
                customer.Department = model.Department == null ? "" : model.Department;
                customer.Position = model.Position == null ? "" : model.Position;
                customer.Memo = model.Memo == null ? "" : model.Memo;

                foreach (var phone in customer.Phones.ToList())
                    entities.DeleteObject(phone);

                var phoneList = model.Phone.Split('◆');
                foreach (var phoneItem in phoneList)
                {
                    if (phoneItem == "")
                        continue;

                    var list = phoneItem.Split('●');
                    Phone phone = new Phone();
                    phone.ID = Guid.NewGuid();
                    phone.Type = list[0];
                    phone.Phone1 = list[1];
                    phone.CustomerID = customer.ID;

                    entities.Phones.AddObject(phone);
                }

                foreach (var email in customer.EMails.ToList())
                    entities.DeleteObject(email);

                var emailList = model.EMail.Split('◆');
                foreach (var emailItem in emailList)
                {
                    if (emailItem == "")
                        continue;

                    var list = emailItem.Split('●');
                    EMail email = new EMail();
                    email.ID = Guid.NewGuid();
                    email.Type = list[0];
                    email.EMail1 = list[1];
                    email.CustomerID = customer.ID;

                    entities.EMails.AddObject(email);
                }

                foreach (var address in customer.Addresses.ToList())
                    entities.DeleteObject(address);

                var addressList = model.Adress.Split('◆');
                foreach (var addressItem in addressList)
                {
                    if (addressItem == "")
                        continue;

                    var list = addressItem.Split('●');
                    Address address = new Address();
                    address.ID = Guid.NewGuid();
                    address.Type = list[0];
                    address.Zip = list[1];
                    address.Province = list[2];
                    address.City = list[3];
                    address.Streat = list[4];
                    address.Country = list[5];
                    address.CustomerID = customer.ID;

                    entities.Addresses.AddObject(address);
                }

                entities.SaveChanges();

                return RedirectToAction("CustomerMgt", new { Message = "儲存完成" });
            }

            return View(model);
        }

        public JsonResult GetEMailTypes()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            List<object> list = new List<object>();
            list.Add(new { Type = "電子郵件" });
            list.Add(new { Type = "電子郵件2" });
            list.Add(new { Type = "電子郵件3" });
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetPhoneTypes()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            List<object> list = new List<object>();
            list.Add(new { Type = "助理" });
            list.Add(new { Type = "商務" });
            list.Add(new { Type = "商務2" });
            list.Add(new { Type = "商務傳真" });
            list.Add(new { Type = "回電話" });
            list.Add(new { Type = "車載電話" });
            list.Add(new { Type = "單位" });
            list.Add(new { Type = "住宅" });
            list.Add(new { Type = "住宅2" });
            list.Add(new { Type = "住宅傳真" });
            list.Add(new { Type = "ISDN" });
            list.Add(new { Type = "移動電話" });
            list.Add(new { Type = "其他" });
            list.Add(new { Type = "其他傳真" });
            list.Add(new { Type = "尋呼機" });
            list.Add(new { Type = "主要電話" });
            list.Add(new { Type = "無線電話" });
            list.Add(new { Type = "電報" });
            list.Add(new { Type = "TTY-TDD" });
            return Json(list, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetAddressTypes()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.CUSTOMER_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            List<object> list = new List<object>();
            list.Add(new { Type = "商務" });
            list.Add(new { Type = "住宅" });
            list.Add(new { Type = "其他" });
            return Json(list, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProductTypeMgt()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            return View();
        }

        public JsonResult GetProductTypes()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            TWCRMEntities entities = new TWCRMEntities();

            var element = (from pt in entities.ProductTypes
                           where pt.ParentID == null
                           select pt).ToList();

            List<ProductTypeModel> list = new List<ProductTypeModel>();

            foreach (var pt in element)
            {
                ProductTypeModel ptm = new ProductTypeModel();

                ptm.ID = pt.ID;
                ptm.Name = pt.Name;
                ptm.FullName = pt.FullName;
                ptm.ParentID = pt.ParentID;

                GetSubProductTypes(ptm);

                list.Add(ptm);
            }

            return Json(list, JsonRequestBehavior.AllowGet);
        }

        void GetSubProductTypes(ProductTypeModel productType)
        {
            TWCRMEntities entities = new TWCRMEntities();

            var element = (from pt in entities.ProductTypes
                           where pt.ParentID == productType.ID
                           select pt).ToList();

            List<ProductTypeModel> list = new List<ProductTypeModel>();

            foreach (var pt in element)
            {
                ProductTypeModel ptm = new ProductTypeModel();

                ptm.ID = pt.ID;
                ptm.Name = pt.Name;
                ptm.FullName = pt.FullName;
                ptm.ParentID = pt.ParentID;

                GetSubProductTypes(ptm);

                list.Add(ptm);
            }

            productType.Children = list;
        }

        public ActionResult ProductTypeEdit(Guid? id, Guid? parentID)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            TWCRMEntities entities = new TWCRMEntities();
            ProductTypeModel model = new ProductTypeModel();

            if (id == null)
            {
                model.IsNew = true;

                if (parentID != null)
                {
                    model.ParentID = parentID;

                    var parent = (from pt in entities.ProductTypes
                                  where pt.ID == parentID
                                  select pt).SingleOrDefault();

                    model.Parent = parent.FullName;
                }
            }
            else
            {
                var element = (from pt in entities.ProductTypes
                               where id == pt.ID
                               select pt).SingleOrDefault();

                if (element == null)
                {
                    return this.RedirectToAction("ProductTypeMgt", new { Error = "找不到這個產品類別" });
                }

                model.ID = element.ID;
                model.ParentID = element.ParentID;
                model.Name = element.Name;
                model.FullName = element.FullName;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult ProductTypeEdit(ProductTypeModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            if (ModelState.IsValid)
            {
                TWCRMEntities entities = new TWCRMEntities();

                ProductType productType;

                if (model.IsNew)
                {
                    productType = new ProductType();
                    productType.ID = Guid.NewGuid();

                    entities.ProductTypes.AddObject(productType);
                }
                else
                {
                    productType = (from c in entities.ProductTypes
                                   where c.ID == model.ID
                                   select c).SingleOrDefault();
                    if (productType == null)
                        return RedirectToAction("ProductTypeMgt", new { Error = "找不到這個產品類別" });
                }

                productType.Name = model.Name == null ? "" : model.Name;
                productType.ParentID = model.ParentID == null ? null : model.ParentID;
                string fullName = productType.Name;
                var parent = (from p in entities.ProductTypes
                              where p.ID == productType.ParentID
                              select p).SingleOrDefault();
                if (parent != null)
                    fullName = string.Format("{0} - {1}", parent.FullName, fullName);
                productType.FullName = fullName;

                updateFullName(productType, entities);

                entities.SaveChanges();

                return RedirectToAction("ProductTypeMgt", new { Message = "儲存完成" });
            }

            return View(model);
        }

        private void updateFullName(ProductType productType, TWCRMEntities entities)
        {
            var list = (from p in entities.ProductTypes
                        where p.ParentID == productType.ID
                        select p);
            foreach (var subType in list)
            {
                subType.FullName = string.Format("{0} - {1}", productType.FullName, subType.Name);
                updateFullName(productType, entities);
            }
        }

        public ActionResult ProductMgt()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            return View();
        }

        public JsonResult GetProducts()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            TWCRMEntities entities = new TWCRMEntities();

            var element = (from p in entities.Products
                           select p).ToList();

            List<ProductModel> list = new List<ProductModel>();

            foreach (var p in element)
            {
                ProductModel pm = new ProductModel();

                pm.ID = p.ID;
                pm.Name = p.Name;
                pm.Brand = p.Brand;
                pm.Model1 = p.Model;
                pm.ListPrice = p.ListPrice;
                pm.ProductTypeID = p.ProductTypeID;
                pm.ProductType = p.ProductType.FullName;

                list.Add(pm);
            }

            return Json(new { List = list }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetProductsByProductType(Guid id)
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            TWCRMEntities entities = new TWCRMEntities();

            var element = (from p in entities.Products
                           where p.ProductTypeID == id
                           select p).ToList();

            List<ProductModel> list = new List<ProductModel>();

            foreach (var p in element)
            {
                ProductModel pm = new ProductModel();

                pm.ID = p.ID;
                pm.Name = p.Name;
                pm.Brand = p.Brand;
                pm.Model1 = p.Model;
                pm.ListPrice = p.ListPrice;
                pm.ProductTypeID = p.ProductTypeID;
                pm.ProductType = p.ProductType.FullName;

                list.Add(pm);
            }

            return Json(new { List = list }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult ProductEdit(Guid? id)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            TWCRMEntities entities = new TWCRMEntities();
            ProductModel model = new ProductModel();

            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                var element = (from p in entities.Products
                               where id == p.ID
                               select p).SingleOrDefault();

                if (element == null)
                {
                    return this.RedirectToAction("ProductMgt", new { Error = "找不到這個產品" });
                }

                model.ID = element.ID;
                model.Name = element.Name;
                model.Brand = element.Brand;
                model.Model1 = element.Model;
                model.ListPrice = element.ListPrice;
                model.ProductTypeID = element.ProductTypeID;
                model.ProductType = element.ProductType.FullName;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult ProductEdit(ProductModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.PRODUCT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            if (ModelState.IsValid)
            {
                TWCRMEntities entities = new TWCRMEntities();

                Product product;

                if (model.IsNew)
                {
                    product = new Product();
                    product.ID = Guid.NewGuid();

                    entities.Products.AddObject(product);
                }
                else
                {
                    product = (from p in entities.Products
                               where p.ID == model.ID
                               select p).SingleOrDefault();
                    if (product == null)
                        return RedirectToAction("ProductMgt", new { Error = "找不到這個產品" });
                }

                product.Name = model.Name == null ? "" : model.Name;
                product.Brand = model.Brand == null ? "" : model.Brand;
                product.Model = model.Model1 == null ? "" : model.Model1;
                product.ListPrice = model.ListPrice == 0 ? 0 : model.ListPrice;
                product.ProductTypeID = model.ProductTypeID == null ? Guid.Empty : model.ProductTypeID;

                entities.SaveChanges();

                return RedirectToAction("ProductMgt", new { Message = "儲存完成" });
            }

            return View(model);
        }

        public ActionResult OrderMgt()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ORDER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            return View();
        }

        public JsonResult GetOrders()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.ORDER_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            TWCRMEntities entities = new TWCRMEntities();

            var element = (from o in entities.Orders
                           select o).ToList();

            List<OrderModel> list = new List<OrderModel>();

            foreach (var o in element)
            {
                OrderModel om = new OrderModel();
                om.ID = o.ID;
                om.Customer = o.Customer.FirstName + " " + o.Customer.LastName;
                om.OrderDate = o.OrderDate;
                om.Date = o.Date;
                om.TotalPrice = o.TotalPrice;

                list.Add(om);
            }

            return Json(new { List = list }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult OrderEdit(Guid? id)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ORDER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            TWCRMEntities entities = new TWCRMEntities();
            OrderModel model = new OrderModel();

            if (id == null)
            {
                model.IsNew = true;
                DateTime now = DateTime.Now;
                model.Date = new DateTime(now.Year, now.Month, now.Day);
            }
            else
            {
                var element = (from o in entities.Orders
                               where id == o.ID
                               select o).SingleOrDefault();

                if (element == null)
                {
                    return this.RedirectToAction("OrderMgt", new { Error = "找不到這張訂單" });
                }

                model.ID = element.ID;

                model.OrderDetails = element.OrderDetails.ToList();
                model.OrderDate = element.OrderDate;
                model.Date = element.Date;
                model.CustomerID = element.CustomerID;
                model.Customer = element.Customer.FirstName + " " + element.Customer.LastName;
                model.TotalPrice = element.TotalPrice;

            }

            return View(model);
        }

        [HttpPost]
        public ActionResult OrderEdit(OrderModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ORDER_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            if (ModelState.IsValid)
            {
                TWCRMEntities entities = new TWCRMEntities();
                Order order = null;

                if (model.IsNew)
                {
                    order = new Order();
                    order.ID = Guid.NewGuid();
                    order.OrderDate = DateTime.Now;
                    order.CustomerID = model.CustomerID;
                    entities.Orders.AddObject(order);
                }
                else
                {
                    order = (from o in entities.Orders
                             where o.ID == model.ID
                             select o).SingleOrDefault();
                    if (order == null)
                        return RedirectToAction("OrderMgt", new { Error = "找不到這張訂單" });
                }

                order.Date = model.Date;
                order.TotalPrice = 0;
                foreach (var detail in order.OrderDetails.ToArray())
                    entities.OrderDetails.DeleteObject(detail);

                var detailList = model.OrderDetail.Split('◆');
                foreach (var detailText in detailList)
                {
                    if (detailText == "")
                        continue;

                    var list = detailText.Split('●');
                    var productID = new Guid(list[0]);
                    OrderDetail detail = new OrderDetail();
                    detail.ID = Guid.NewGuid();
                    detail.OrderID = order.ID;
                    if (productID == Guid.Empty)
                    {
                        detail.ProductID = null;
                        detail.ProductName = list[1];
                        detail.ProductType = list[2];
                        detail.ProductBrand = list[3];
                        detail.ProductModel = list[4];
                        detail.ListPrice = null;
                    }
                    else
                    {
                        var product = (from p in entities.Products
                                       where p.ID == productID
                                       select p).SingleOrDefault();
                        detail.ProductID = product.ID;
                        detail.ProductName = product.Name;
                        detail.ProductType = product.ProductType.FullName;
                        detail.ProductBrand = product.Brand;
                        detail.ProductModel = product.Model;
                        detail.ListPrice = product.ListPrice;
                    }
                    detail.Price = Convert.ToDecimal(list[5]);
                    detail.Qty = Convert.ToInt32(list[6]);
                    detail.TotalPrice = detail.Price * detail.Qty;
                    order.TotalPrice += detail.TotalPrice;

                    entities.OrderDetails.AddObject(detail);
                }

                entities.SaveChanges();

                return RedirectToAction("OrderMgt", new { Message = "儲存完成" });
            }

            return View(model);
        }

        public ActionResult AccountMgt()
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ACCOUNT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            return View();
        }

        public JsonResult GetAccounts()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.ACCOUNT_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            TWCRMEntities entities = new TWCRMEntities();

            var element = (from u in entities.Users
                           select u).ToList();

            List<AccountModel> list = new List<AccountModel>();

            foreach (var u in element)
            {
                AccountModel am = new AccountModel();
                am.ID = u.ID;
                am.Name = u.Name;
                am.Effective = u.Effective;

                list.Add(am);
            }

            return Json(new { List = list }, JsonRequestBehavior.AllowGet);
        }

        public ActionResult AccountEdit(Guid? id)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ACCOUNT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            TWCRMEntities entities = new TWCRMEntities();
            AccountModel model = new AccountModel();
            if (id == null)
            {
                model.IsNew = true;
            }
            else
            {
                var element = (from u in entities.Users
                               where id == u.ID
                               select u).SingleOrDefault();

                if (element == null)
                {
                    return this.RedirectToAction("AccountMgt", new { Error = "找不到這個帳戶" });
                }

                model.ID = element.ID;
                model.AuthorityList = element.UserAuthorities.ToList();
                model.Name = element.Name;
                model.Password = element.Password;
                model.Effective = element.Effective;
            }

            return View(model);
        }

        [HttpPost]
        public ActionResult AccountEdit(AccountModel model)
        {
            if (!checkLogin())
                return this.RedirectToAction("Login");
            if (!checkAuthority(ConstAuthority.ACCOUNT_MGT))
                return this.RedirectToAction("Index", new { Error = "您沒有這個權限" });

            if (ModelState.IsValid)
            {
                TWCRMEntities entities = new TWCRMEntities();
                User user = null;

                if (model.IsNew)
                {
                    user = new User();
                    user.ID = Guid.NewGuid();
                    user.Name = model.Name;
                    user.Password = model.Password;
                    entities.Users.AddObject(user);
                }
                else
                {
                    user = (from u in entities.Users
                            where u.ID == model.ID
                            select u).SingleOrDefault();
                    if (user == null)
                        return RedirectToAction("AccountMgt", new { Error = "找不到這個帳戶" });
                }

                foreach (var detail in user.UserAuthorities.ToArray())
                    entities.UserAuthorities.DeleteObject(detail);

                user.Effective = false;

                var detailList = model.Authority.Split('◆');
                foreach (var detailText in detailList)
                {
                    if (detailText == "")
                        continue;

                    var list = detailText.Split('●');

                    UserAuthority detail = new UserAuthority();
                    detail.ID = Guid.NewGuid();
                    detail.UserID = user.ID;
                    detail.Authority = list[0];
                    detail.Allow = list[1] == "checked" ? true : false;

                    if (detail.Allow)
                        user.Effective = true;

                    entities.UserAuthorities.AddObject(detail);
                }

                entities.SaveChanges();

                return RedirectToAction("AccountMgt", new { Message = "儲存完成" });
            }

            return View(model);
        }

        public JsonResult GetAuthoritys()
        {
            if (!checkLogin())
                return Json(null, JsonRequestBehavior.AllowGet);
            if (!checkAuthority(ConstAuthority.ACCOUNT_MGT))
                return Json(null, JsonRequestBehavior.AllowGet);

            List<object> list = new List<object>();
            list.Add(new { Authority = ConstAuthority.CUSTOMER_MGT });
            list.Add(new { Authority = ConstAuthority.ORDER_MGT });
            list.Add(new { Authority = ConstAuthority.PRODUCT_MGT });
            list.Add(new { Authority = ConstAuthority.ACCOUNT_MGT });
            return Json(list, JsonRequestBehavior.AllowGet);
        }
    }

    public class ConstAuthority
    {
        public const string CUSTOMER_MGT = "客戶管理";
        public const string ORDER_MGT = "訂單管理";
        public const string PRODUCT_MGT = "產品管理";
        public const string ACCOUNT_MGT = "帳戶管理";
    }
}